<?php

namespace app\common\controller;

use app\common\exception\MyException;
use app\common\controller\Base;
use app\common\service\sys\UserService;
use app\common\service\sys\ClientService;

/**
 * API权限控制器基类
 * @author kaige
 * @copyright ©2022 泉州市盛筑信息科技有限公司 版权所有
 * @update 2022-05-23
 */
class ApiBasic extends Base
{
    /**
     * 用户信息
     */
    protected $user;
    /**
     * 节点
     */
    protected $knode;
    /**
     * 设置当前服务
     */
    protected $service;
    /**
     * 系统字典
     */
    protected $sysdict;

    /**
     * 初始化 不能用 return 只能exit
     */
    protected function initialize()
    {
        parent::initialize();
        // 验证签名
        $appid = $this->request->header('Kg-Appid');
        if (empty($appid)) {
            throw new MyException(['code' => 1002]);
        }
        // 实时数据
        $app = (new ClientService())->getInfoByName($appid);
        // 是否存在
        if (empty($app)) {
            throw new MyException(['code' => 2001]);
        }
        // 状态
        if (empty($app) || $app['status'] != 1) {
            throw new MyException(['code' => 2002]);
        }
        // 客户端应用ID
        // $this->request->client_appid = $appid;

        $appsignwhite = config("kaige.app_sign_white_url");
        list($module, $controller, $action) = [app('http')->getName(), strtolower($this->request->controller()), $this->request->action()];
        $this->knode = $module . '/' . $controller . '/' . strtolower($action); // 方法只允许小写
        $this->knode = parseNodeStr($this->knode);
        // 免签白名单
        $whilesign = false;
        if ($this->knode && $appsignwhite && in_array($this->knode, $appsignwhite)) {
            $whilesign = true;
        }

        // 接口签名认证
        if (config("kaige.app_sign_auth_on") === true && $whilesign === false) {
            // app端生成的签名
            $param = $this->request->param();
           
            $sign = $this->request->param("signature"); //前端过来的是signature
            unset($param['signature']);
            if (empty($sign)) {
                throw new MyException(['code' => 2003]);
            }
            //数组排序
            ksort($param);
            foreach($param as $k9=>&$v9){//一层数组排一下序
                if(is_array($v9)){
                    ksort($v9);
                }
            }
            $str = http_build_query($param);
            $sign1 = md5(sha1($str) . $app['app_salt']);
            if ($sign != $sign1) {
                throw new MyException(['code' => 2004]);
            }
        }

        $token = $this->request->header('Kg-Token');
        if(empty($token) || $token == 'false' || $token === false){
            throw new MyException(['code' => 2101]);
            exit;
        }

        //验证身份（登录）
        $user = (new UserService())->checkAdmin($token,_gip());
        $this->user = $user['user'];

        //取出字典
        $this->sysdict = \app\common\service\sys\DictService::getDictAll(env('COMPANY_ID', 11));//默认 盛筑科技 ID 11
        
    }
}
